import React, { useEffect } from 'react';
import { Select, Space } from 'antd';
import dayjs from 'dayjs';
import weekOfYear from 'dayjs/plugin/weekOfYear';
import 'dayjs/locale/zh-cn';

dayjs.extend(weekOfYear);
dayjs.locale('zh-cn');

interface WeekPickerProps {
  value?: string;
  onChange?: (value: string) => void;
}

const WeekPicker: React.FC<WeekPickerProps> = ({ value, onChange }) => {
  // 获取当前年份
  const currentYear = dayjs().year();
  
  // 生成年份选项
  const yearOptions = Array.from({ length: 5 }, (_, i) => ({
    value: currentYear - 2 + i,
    label: `${currentYear - 2 + i}年`
  }));

  // 生成月份选项
  const monthOptions = Array.from({ length: 12 }, (_, i) => ({
    value: i + 1,
    label: `${i + 1}月`
  }));

  // 生成周数选项
  const weekOptions = Array.from({ length: 5 }, (_, i) => ({
    value: i + 1,
    label: `第${i + 1}周`
  }));

  // 计算当前日期是当月的第几周
  const calculateCurrentWeek = () => {
    const now = dayjs();
    const currentDay = now.date();
    // 直接按照每7天为一周来计算
    // 1-7号为第1周，8-14号为第2周，以此类推
    return Math.ceil(currentDay / 7);
  };

  // 解析当前值
  const [year, month, week] = value ? value.split('-').map(Number) : [
    currentYear, 
    dayjs().month() + 1, 
    calculateCurrentWeek()
  ];

  // 组件初始化时，如果没有传入value，则设置默认值
  useEffect(() => {
    if (!value) {
      const currentWeek = calculateCurrentWeek();
      onChange?.(`${currentYear}-${dayjs().month() + 1}-${currentWeek}`);
    }
  }, []);

  // 处理年份变化
  const handleYearChange = (newYear: number) => {
    onChange?.(`${newYear}-${month}-${week}`);
  };

  // 处理月份变化
  const handleMonthChange = (newMonth: number) => {
    onChange?.(`${year}-${newMonth}-${week}`);
  };

  // 处理周数变化
  const handleWeekChange = (newWeek: number) => {
    onChange?.(`${year}-${month}-${newWeek}`);
  };

  return (
    <Space>
      <Select
        value={year}
        onChange={handleYearChange}
        options={yearOptions}
        style={{ width: 90 }}
      />
      <Select
        value={month}
        onChange={handleMonthChange}
        options={monthOptions}
        style={{ width: 71 }}
      />
      <Select
        value={week}
        onChange={handleWeekChange}
        options={weekOptions}
        style={{ width: 75 }}
      />
    </Space>
  );
};

export default WeekPicker; 